package dnacos

import (
	"fmt"
	"gitee.com/dingyangzhuang/dingutils/dlog/logger"
	"github.com/nacos-group/nacos-sdk-go/v2/model"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"gopkg.in/resty.v1"
)

// 获取一个健康的实例
/**
具体调用
func hello(c *gin.Context) {
	name := c.Param("name")
	instance := selectOneHealthyInstance(NamingClient, "server-java")
	url := fmt.Sprintf("http://%s:%d/hello/%s", instance.Ip, instance.Port, name)
	resp, _ := http.Get(url)
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	c.String(http.StatusOK, string(body))
}

*/
func (n NacosConfigClient[T]) SelectOneHealthyInstance(serviceName string, group string, cluster string) (*model.Instance, error) {
	instances, err := n.serviceClient.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
		ServiceName: serviceName,
		GroupName:   group,
		Clusters:    []string{cluster},
	})
	if err != nil {
		logger.Error("获取实例错误", "msg", err.Error())
		return nil, err
	}
	return instances, nil
}

// 默认调用Post方法，返回resp
func (n NacosConfigClient[T]) DefaultSelectOneHealthyInstanceToExcute(serviceName string, group string, cluster string, payload map[string]string, path string) (*resty.Response, error) {
	instance, err := n.SelectOneHealthyInstance(serviceName, group, cluster)
	if err != nil {
		return nil, err
	}
	client1 := resty.New()
	//payload := map[string]string{
	//	"ip":       "10.114.102.164",
	//	"port":     "22",
	//	"instruct": "execute",
	//	"args":     "ls -la;;ls -la /tmp",
	//	"password": "7RmeNTAsy0Krs55G+7/orw==",
	//	"user":     "mxadmin",
	//}
	resp, err := client1.R().
		SetBody(payload).
		Post(fmt.Sprintf("http://%s:%d/%s", instance.Ip, instance.Port, path))

	if err != nil {
		logger.Error("执行微服务调用失败", "path", path, "serviceName", serviceName, "body", payload, "msg", err.Error())
		return nil, err
	}
	return resp, nil
}
